%     AERO LOAD - программа для нагружения агрегатов самолета распределенной нагрузкой
%     Copyright (C) 2018-2024  Михаил Козлов
%     Сайт проекта: <http://www.fastenerdoctor.ru/>
%     Адрес электронной почты для связи с разработчиком:
%     <doctor.fastener@gmail.com>
% 
%     Эта программа является свободным программным обеспечением: Вы можете
%     распространять ее и/или изменять, соблюдая условия Универсальной общественной
%     лицензии GNU, опубликованной Фондом свободного программного обеспечения,
%     либо редакции 3, либо (на Ваше усмотрение) любой редакции, выпущенной позже.
% 
%     Эта программа распространяется в надежде на то, что она окажется полезной,
%     но БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ, включая даже подразумеваемую гарантию ТОВАРНОЙ ПРИГОДНОСТИ,
%     либо ПРИГОДНОСТИ ДЛЯ ОПРЕДЕЛЕННЫХ ЦЕЛЕЙ. Ознакомьтесь с Универсальной общественной
%     лицензией GNU для получения более подробной информации.
% 
%     Вы должны были получить копию Универсальной общественной лицензии GNU
%     вместе с этой программой. Если Вы ее не получили, то перейдите по адресу:
%     <http://www.gnu.org/licenses/>.
% 
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
% 
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%     GNU General Public License for more details.
% 
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <https://www.gnu.org/licenses/>.

function GW_Plot_Erase_Mesh(src,~)

global Graphic_Window_Handle;
global Graphics_Properties;
global Graphics;

global DB_ELEMENTS;
global AT_NODES;
global DB_NODES;
global PROJECTED_NODES;

Axes_Handle = findall(Graphic_Window_Handle, 'Tag', 'Main_Axes');

switch src.Tag
    
    case 'Plot_Mesh_Button'
        
        % Erase
        tmp.Value = 1;
        tmp.Tag = 'Erase_Mesh_Button';
        GW_Plot_Erase_Mesh(tmp,[]);
        
        % Сетка
        tmp.Value = 1;
        tmp.Tag = 'Draw_Mesh_Button';
        GW_Plot_Erase_Mesh(tmp,[]);
        set(findall(Graphic_Window_Handle, 'Tag', tmp.Tag), 'Value', 1);
        
    case 'Erase_Mesh_Button'
        
        % Сетка
        tmp.Value = 0;
        tmp.Tag = 'Draw_Mesh_Button';
        GW_Plot_Erase_Mesh(tmp,[]);
        set(findall(Graphic_Window_Handle, 'Tag', tmp.Tag), 'Value', 0);
        
        % Проекция сетки
        tmp.Value = 0;
        tmp.Tag = 'Draw_Projected_Mesh_Button';
        GW_Plot_Erase_Mesh(tmp,[]);
        set(findall(Graphic_Window_Handle, 'Tag', tmp.Tag), 'Value', 0);
        
    case 'Draw_Mesh_Button'
        
        Slider_Handle = findall(Graphic_Window_Handle, 'Tag', 'Mesh_Translucency_Slider');
        
        if (src.Value == 1)
            
            Max_Elm_Nodes = 0;

            for i=1:size(DB_ELEMENTS,1)

                if (DB_ELEMENTS{i}.N_nodes > Max_Elm_Nodes)
                    Max_Elm_Nodes = DB_ELEMENTS{i}.N_nodes;
                end

            end

            MESH_NODES = zeros(size(AT_NODES,1), 3);
            MESH_ELEMENTS = NaN(size(DB_ELEMENTS,1), Max_Elm_Nodes);

            for i=1:size(AT_NODES,1)

                if (AT_NODES(i) ~= 0)

                    MESH_NODES(i,:) = DB_NODES{AT_NODES(i)}.Location';

                end

            end

            for i=1:size(DB_ELEMENTS,1)

                switch DB_ELEMENTS{i}.N_nodes

                    case 3

                        MESH_ELEMENTS(i,1:DB_ELEMENTS{i}.N_nodes) = DB_ELEMENTS{i}.Nodes';

                    case 4

                        MESH_ELEMENTS(i,1:DB_ELEMENTS{i}.N_nodes) = DB_ELEMENTS{i}.Nodes';

                    case 6

                        MESH_ELEMENTS(i,1) = DB_ELEMENTS{i}.Nodes(1);
                        MESH_ELEMENTS(i,2) = DB_ELEMENTS{i}.Nodes(4);
                        MESH_ELEMENTS(i,3) = DB_ELEMENTS{i}.Nodes(2);
                        MESH_ELEMENTS(i,4) = DB_ELEMENTS{i}.Nodes(5);
                        MESH_ELEMENTS(i,5) = DB_ELEMENTS{i}.Nodes(3);
                        MESH_ELEMENTS(i,6) = DB_ELEMENTS{i}.Nodes(6);

                    case 8

                        MESH_ELEMENTS(i,1) = DB_ELEMENTS{i}.Nodes(1);
                        MESH_ELEMENTS(i,2) = DB_ELEMENTS{i}.Nodes(5);
                        MESH_ELEMENTS(i,3) = DB_ELEMENTS{i}.Nodes(2);
                        MESH_ELEMENTS(i,4) = DB_ELEMENTS{i}.Nodes(6);
                        MESH_ELEMENTS(i,5) = DB_ELEMENTS{i}.Nodes(3);
                        MESH_ELEMENTS(i,6) = DB_ELEMENTS{i}.Nodes(7);
                        MESH_ELEMENTS(i,7) = DB_ELEMENTS{i}.Nodes(4);
                        MESH_ELEMENTS(i,8) = DB_ELEMENTS{i}.Nodes(8);

                end

            end
            
            Edge_Color = Graphics_Properties.Element_Edge_Color;
            
            if (isequal(get(Graphic_Window_Handle, 'Color'), [0 0 0]))
                if (get(findall(Graphic_Window_Handle, 'Tag', 'Mesh_Translucency_Slider'), 'Value') < Graphics_Properties.Element_Edge_Color_Threshold)
                    Edge_Color = Graphics_Properties.Element_Edge_Color_Bright;
                end
            end
            
            patch(Axes_Handle, 'Vertices', MESH_NODES, ...
                               'Faces', MESH_ELEMENTS, ...
                               'FaceColor', Graphics_Properties.Element_Face_Color, ...
                               'EdgeColor', Edge_Color, ...
                               'FaceAlpha', Slider_Handle.Value, ...
                               'Tag', 'Mesh');
            
            % Активировать кнопку
            set(findall(Graphic_Window_Handle, 'Tag', 'Draw_Normals_Button'), 'Enable', 'on');
            set(findall(Graphic_Window_Handle, 'Tag', 'Mesh_Translucency_Slider'), 'Enable', 'on');
            set(findall(Graphic_Window_Handle, 'Tag', 'Mesh_Translucency_Text'), 'Enable', 'on');
            
        else
            
            % Удалить данные и деактивировать кнопку
            tmp.Value = 0;
            tmp.Tag = 'Draw_Normals_Button';
            GW_Plot_Erase_Mesh(tmp,[]);
            set(findall(Graphic_Window_Handle, 'Tag', tmp.Tag), 'Value', 0, 'Enable', 'off');
            
            % Деактивировать кнопку
            set(findall(Graphic_Window_Handle, 'Tag', 'Mesh_Translucency_Slider'), 'Enable', 'off');
            set(findall(Graphic_Window_Handle, 'Tag', 'Mesh_Translucency_Text'), 'Enable', 'off');
            
            delete(findall(Graphic_Window_Handle, 'Tag', 'Mesh'));
            
        end
        
    case 'Mesh_Translucency_Slider'
        
        set(findall(Graphic_Window_Handle, 'Tag', 'Mesh'), 'FaceAlpha', src.Value);
        set(findall(Graphic_Window_Handle, 'Tag', 'Mesh_Translucency_Text'), 'String', sprintf('%.2f', src.Value));
        
        if (isequal(get(Graphic_Window_Handle, 'Color'), [0 0 0]))
            if (src.Value < Graphics_Properties.Element_Edge_Color_Threshold)
                set(findall(Graphic_Window_Handle, 'Tag', 'Mesh'), 'EdgeColor', Graphics_Properties.Element_Edge_Color_Bright);
            else
                set(findall(Graphic_Window_Handle, 'Tag', 'Mesh'), 'EdgeColor', Graphics_Properties.Element_Edge_Color);
            end
        end
        
    case 'Draw_Normals_Button'
        
        if (src.Value == 1)
            
            Tmp = nan(11*size(DB_ELEMENTS,1), 3);
            
            for i=1:size(DB_ELEMENTS,1)
                
                Centroid = Get_Shell_Centroid(DB_ELEMENTS{i}.ID);
                Normal_vector = Get_Shell_Normal(DB_ELEMENTS{i}.ID);
                
                Tmp_Vector_1 = Graphics.Load.Chord_Surface.A1_projected - Graphics.Load.Chord_Surface.A2_projected;
                Tmp_Vector_1 = Tmp_Vector_1/norm(Tmp_Vector_1);

                Tmp_Vector_2 = cross(Tmp_Vector_1, Normal_vector);
                Tmp_Vector_2 = Tmp_Vector_2/norm(Tmp_Vector_2);
                
                Tmp_Vector_1 = cross(Normal_vector, Tmp_Vector_2);
                Tmp_Vector_1 = Tmp_Vector_1/norm(Tmp_Vector_1);
                
                Tmp(11*i-10,:) = Centroid';
                Tmp(11*i-9,:) = Tmp(11*i-10,:) + Normal_vector' * Graphics.Normal_Length;
                Tmp(11*i-8,:) = Tmp(11*i-9,:) - (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_1)' - (Normal_vector*Graphics.Normal_Length * Graphics_Properties.Normal_Arrow_Size_1)';
                Tmp(11*i-7,:) = Tmp(11*i-8,:) + (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_1)';
                Tmp(11*i-6,:) = Tmp(11*i-7,:) + (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_2)';
                Tmp(11*i-5,:) = Tmp(11*i-6,:) - (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_2)' + (Normal_vector*Graphics.Normal_Length * Graphics_Properties.Normal_Arrow_Size_1)';
                Tmp(11*i-4,:) = Tmp(11*i-5,:) + (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_1)' - (Normal_vector*Graphics.Normal_Length * Graphics_Properties.Normal_Arrow_Size_1)';
                Tmp(11*i-3,:) = Tmp(11*i-4,:) - (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_1)';
                Tmp(11*i-2,:) = Tmp(11*i-3,:) - (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_2)';
                Tmp(11*i-1,:) = Tmp(11*i-9,:);
                
            end
            
            Vector_Plot_Handle = plot3(Axes_Handle, Tmp(:,1), Tmp(:,2), Tmp(:,3));

            set(Vector_Plot_Handle, 'Color', Graphics_Properties.Element_Normal_Color);
            set(Vector_Plot_Handle, 'Tag', 'Normals');
            
        else
            
            delete(findall(Graphic_Window_Handle, 'Tag', 'Normals'));
            
        end
        
    case 'Draw_Projected_Mesh_Button'
        
        Slider_Handle = findall(Graphic_Window_Handle, 'Tag', 'Projected_Mesh_Translucency_Slider');
        
        if (src.Value == 1)
            
            Max_Elm_Nodes = 0;

            for i=1:size(DB_ELEMENTS,1)

                if (DB_ELEMENTS{i}.N_nodes > Max_Elm_Nodes)
                    Max_Elm_Nodes = DB_ELEMENTS{i}.N_nodes;
                end

            end

            MESH_NODES_PROJECTED = zeros(size(AT_NODES,1), 3);
            MESH_ELEMENTS = NaN(size(DB_ELEMENTS,1), Max_Elm_Nodes);

            for i=1:size(AT_NODES,1)

                if (AT_NODES(i) ~= 0)

                    MESH_NODES_PROJECTED(i,:) = PROJECTED_NODES(AT_NODES(i),:);

                end

            end

            for i=1:size(DB_ELEMENTS,1)

                switch DB_ELEMENTS{i}.N_nodes

                    case 3

                        MESH_ELEMENTS(i,1:DB_ELEMENTS{i}.N_nodes) = DB_ELEMENTS{i}.Nodes';

                    case 4

                        MESH_ELEMENTS(i,1:DB_ELEMENTS{i}.N_nodes) = DB_ELEMENTS{i}.Nodes';

                    case 6

                        MESH_ELEMENTS(i,1) = DB_ELEMENTS{i}.Nodes(1);
                        MESH_ELEMENTS(i,2) = DB_ELEMENTS{i}.Nodes(4);
                        MESH_ELEMENTS(i,3) = DB_ELEMENTS{i}.Nodes(2);
                        MESH_ELEMENTS(i,4) = DB_ELEMENTS{i}.Nodes(5);
                        MESH_ELEMENTS(i,5) = DB_ELEMENTS{i}.Nodes(3);
                        MESH_ELEMENTS(i,6) = DB_ELEMENTS{i}.Nodes(6);

                    case 8

                        MESH_ELEMENTS(i,1) = DB_ELEMENTS{i}.Nodes(1);
                        MESH_ELEMENTS(i,2) = DB_ELEMENTS{i}.Nodes(5);
                        MESH_ELEMENTS(i,3) = DB_ELEMENTS{i}.Nodes(2);
                        MESH_ELEMENTS(i,4) = DB_ELEMENTS{i}.Nodes(6);
                        MESH_ELEMENTS(i,5) = DB_ELEMENTS{i}.Nodes(3);
                        MESH_ELEMENTS(i,6) = DB_ELEMENTS{i}.Nodes(7);
                        MESH_ELEMENTS(i,7) = DB_ELEMENTS{i}.Nodes(4);
                        MESH_ELEMENTS(i,8) = DB_ELEMENTS{i}.Nodes(8);

                end

            end
            
            Edge_Color = Graphics_Properties.Element_Edge_Color;
            
            if (isequal(get(Graphic_Window_Handle, 'Color'), [0 0 0]))
                if (get(findall(Graphic_Window_Handle, 'Tag', 'Projected_Mesh_Translucency_Slider'), 'Value') < Graphics_Properties.Element_Edge_Color_Threshold)
                    Edge_Color = Graphics_Properties.Element_Edge_Color_Bright;
                end
            end
            
            patch(Axes_Handle, 'Vertices', MESH_NODES_PROJECTED, ...
                               'Faces', MESH_ELEMENTS, ...
                               'FaceColor', Graphics_Properties.Element_Face_Color, ...
                               'EdgeColor', Edge_Color, ...
                               'FaceAlpha', Slider_Handle.Value, ...
                               'Tag', 'Projected_Mesh');
            
            % Активировать кнопку
            set(findall(Graphic_Window_Handle, 'Tag', 'Draw_Projected_Normals_Button'), 'Enable', 'on');
            set(findall(Graphic_Window_Handle, 'Tag', 'Projected_Mesh_Translucency_Slider'), 'Enable', 'on');
            set(findall(Graphic_Window_Handle, 'Tag', 'Projected_Mesh_Translucency_Text'), 'Enable', 'on');
            
        else
            
            % Удалить данные и деактивировать кнопку
            tmp.Value = 0;
            tmp.Tag = 'Draw_Projected_Normals_Button';
            GW_Plot_Erase_Mesh(tmp,[]);
            set(findall(Graphic_Window_Handle, 'Tag', tmp.Tag), 'Value', 0, 'Enable', 'off');
            
            % Деактивировать кнопку
            set(findall(Graphic_Window_Handle, 'Tag', 'Projected_Mesh_Translucency_Slider'), 'Enable', 'off');
            set(findall(Graphic_Window_Handle, 'Tag', 'Projected_Mesh_Translucency_Text'), 'Enable', 'off');
            
            delete(findall(Graphic_Window_Handle, 'Tag', 'Projected_Mesh'));
            
        end
        
    case 'Projected_Mesh_Translucency_Slider'
        
        set(findall(Graphic_Window_Handle, 'Tag', 'Projected_Mesh'), 'FaceAlpha', src.Value);
        set(findall(Graphic_Window_Handle, 'Tag', 'Projected_Mesh_Translucency_Text'), 'String', sprintf('%.2f', src.Value));
        
        if (isequal(get(Graphic_Window_Handle, 'Color'), [0 0 0]))
            if (src.Value < Graphics_Properties.Element_Edge_Color_Threshold)
                set(findall(Graphic_Window_Handle, 'Tag', 'Projected_Mesh'), 'EdgeColor', Graphics_Properties.Element_Edge_Color_Bright);
            else
                set(findall(Graphic_Window_Handle, 'Tag', 'Projected_Mesh'), 'EdgeColor', Graphics_Properties.Element_Edge_Color);
            end
        end
        
    case 'Draw_Projected_Normals_Button'
        
        if (src.Value == 1)
            
            Tmp = nan(11*size(DB_ELEMENTS,1), 3);
            
            for i=1:size(DB_ELEMENTS,1)
                
                Centroid = Project_Point_To_Plane(Get_Shell_Centroid(DB_ELEMENTS{i}.ID), Graphics.Load.Basic_Plane.Equation);
                
                if (dot(Get_Shell_Normal(DB_ELEMENTS{i}.ID), Graphics.Load.Vector) >= 0)
                    Normal_vector = Graphics.Load.Vector;
                else
                    Normal_vector = -Graphics.Load.Vector;
                end
                
                Tmp_Vector_1 = Graphics.Load.Chord_Surface.A1_projected - Graphics.Load.Chord_Surface.A2_projected;
                Tmp_Vector_1 = Tmp_Vector_1/norm(Tmp_Vector_1);

                Tmp_Vector_2 = cross(Tmp_Vector_1, Normal_vector);
                Tmp_Vector_2 = Tmp_Vector_2/norm(Tmp_Vector_2);
                
                Tmp_Vector_1 = cross(Normal_vector, Tmp_Vector_2);
                Tmp_Vector_1 = Tmp_Vector_1/norm(Tmp_Vector_1);
                
                Tmp(11*i-10,:) = Centroid';
                Tmp(11*i-9,:) = Tmp(11*i-10,:) + Normal_vector' * Graphics.Normal_Length;
                Tmp(11*i-8,:) = Tmp(11*i-9,:) - (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_1)' - (Normal_vector*Graphics.Normal_Length * Graphics_Properties.Normal_Arrow_Size_1)';
                Tmp(11*i-7,:) = Tmp(11*i-8,:) + (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_1)';
                Tmp(11*i-6,:) = Tmp(11*i-7,:) + (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_2)';
                Tmp(11*i-5,:) = Tmp(11*i-6,:) - (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_2)' + (Normal_vector*Graphics.Normal_Length * Graphics_Properties.Normal_Arrow_Size_1)';
                Tmp(11*i-4,:) = Tmp(11*i-5,:) + (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_1)' - (Normal_vector*Graphics.Normal_Length * Graphics_Properties.Normal_Arrow_Size_1)';
                Tmp(11*i-3,:) = Tmp(11*i-4,:) - (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_1)';
                Tmp(11*i-2,:) = Tmp(11*i-3,:) - (Graphics_Properties.Normal_Arrow_Size_2 * Graphics.Normal_Length * Tmp_Vector_2)';
                Tmp(11*i-1,:) = Tmp(11*i-9,:);
                
            end
            
            Vector_Plot_Handle = plot3(Axes_Handle, Tmp(:,1), Tmp(:,2), Tmp(:,3));

            set(Vector_Plot_Handle, 'Color', Graphics_Properties.Element_Normal_Color);
            set(Vector_Plot_Handle, 'Tag', 'Projected_Normals');
            
        else
            
            delete(findall(Graphic_Window_Handle, 'Tag', 'Projected_Normals'));
            
        end
        
end
